package com.ruoyi.yz.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.HashMap;

public class QRCodeUtil {

    public static void Encode2File(String text, int width, int height, String outputPath, String format) throws WriterException, IOException {
        BitMatrix matrix = Encode(text, width, height);

        MatrixToImageWriter.writeToPath(matrix, format, Paths.get(outputPath));
    }

    public static void Encode2Stream(String text, int width, int height, OutputStream stream, String format) throws IOException, WriterException {
        BitMatrix matrix = Encode(text, width, height);

        MatrixToImageWriter.writeToStream(matrix, format, stream);
    }

    private static BitMatrix Encode(String text, int width, int height) throws WriterException {
        HashMap<EncodeHintType, String> hintType = new HashMap<>();
        hintType.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hintType);

        return matrix;
    }
}
